﻿/*
 ***************************************************************************
 * Microsoft Visual C# .NET
 * 名称：       App_Input_HealthTherapyUpdForm
 * 类型：       控制层
 * 功能说明：   健康管家-治疗计划维护页面
 * 作者：       章 昕
 * 创建日期：   2007/09/13
 * 修改日期     修改者      修改内容
 * 
 * 
 * ---
 ***************************************************************************
*/
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Shpm.System.Validator;
using Shpm.System.Web.Control;
using log4net;
using Shpm.App.Input.Bean;
using Shpm.App.Input.Dao;
using Shpm.App.Commons.Db.Beans.Master;
using Shpm.System;
using Shpm.App.Commons.Utils;

public partial class App_Input_HealthTherapyUpdForm : System.Web.UI.Page
{
    // log
    protected static ILog log = LogManager.GetLogger(typeof(App_Input_HealthTherapyUpdForm));


    // page load
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            // 取得当前登录的医生id信息
            SysUserManager manager = new SysUserManager(Context);
            SysUserBean sysUserBean = manager.getSysUserBean();
            MstSysUserBean mstSysUserBean =
                sysUserBean == null ? null : sysUserBean.getMstSysUserBean();
            MstEmployeeBean mstEmpBean =
                sysUserBean == null ? null : sysUserBean.getEmployeeBean();
            string loginId = mstSysUserBean == null ? "" : mstSysUserBean.SysUserId;
            string emplyId = mstSysUserBean == null ? "" : mstSysUserBean.EmployeeId;
            //string emplyRole = mstEmpBean == null ? "" : mstEmpBean.Role;
            //string emplyJob = mstEmpBean == null ? "" : mstEmpBean.EmployeeJob;
            //string emplyLev = mstEmpBean == null ? "" : mstEmpBean.EmployeeLevel;

            ViewState["DOCTOR_ID"] = emplyId;
            ViewState["USER_ID"] = loginId;

            // 接收传递参数为分页编号
            if (Context.Items.Contains("ParamPageIndex"))
            {
                ViewState["ParamPageIndex"] = Context.Items["ParamPageIndex"];
            }

            ViewState["CURE_ID"] = Convert.ToString(Context.Items["CURE_ID"]);
            ViewState["MEMB_ID"] = Convert.ToString(Context.Items["MEMB_ID"]);
            if (Context.Items.Contains("MemberNo"))
            {
                this.ViewState["MemberNo"] = Convert.ToString(Context.Items["MemberNo"]);
            }
            if (Context.Items.Contains("Sex"))
            {
                this.ViewState["Sex"] = Convert.ToString(Context.Items["Sex"]);
            }
            if (Context.Items.Contains("BuildingNo"))
            {
                this.ViewState["BuildingNo"] = Convert.ToString(Context.Items["BuildingNo"]);

            }
            if (Context.Items.Contains("FloorNo"))
            {
                this.ViewState["FloorNo"] = Convert.ToString(Context.Items["FloorNo"]);
            }
            if (Context.Items.Contains("Room"))
            {
                this.ViewState["Room"] = Convert.ToString(Context.Items["Room"]);
            }

            // 初始化控件
            initPageControls();

            // get data

            bindSelectData(Convert.ToString(ViewState["CURE_ID"]), Convert.ToString(ViewState["MEMB_ID"]));

        }
    }

    // 新建治疗计划
    protected void btnNew_Click(object sender, EventArgs e)
    {
        resetFormControls();
    }

    // 登记按钮
    protected void btnOk_Click(object sender, EventArgs e)
    {
        try
        {
            // do validate check
            ComValidateChecker vd = new ComValidateChecker();
            vd.CheckItems.Add(new CheckRequired(txtCureName.Text, new ComMessage("E0094", "治疗项目")));
            vd.CheckItems.Add(new CheckRequired(txtBeginDate.Text, new ComMessage("E0094", "治疗开始日期")));
            vd.CheckItems.Add(new CheckRequired(txtEndDate.Text, new ComMessage("E0094", "治疗结束日期")));
            vd.CheckItems.Add(new CheckRequired(txtFrequency.Text, new ComMessage("E0094", "治疗间隔")));
            vd.CheckItems.Add(new CheckRequired(txtBookDate.Text, new ComMessage("E0094", "下次治疗日期")));

            vd.CheckItems.Add(new CheckLong(txtFrequency.Text, new ComMessage("E0322", "治疗间隔")));
            vd.CheckItems.Add(new CheckLongMore(txtFrequency.Text, 1, new ComMessage("E0065", new string[] { "治疗间隔", "1", "180" })));
            vd.CheckItems.Add(new CheckLongLess(txtFrequency.Text, 180, new ComMessage("E0065", new string[] { "治疗间隔", "1", "180" })));
            vd.CheckItems.Add(new CheckDate(txtBeginDate.Text, "yyyy/MM/dd", new ComMessage("E0037", "治疗开始日期")));
            vd.CheckItems.Add(new CheckDate(txtEndDate.Text, "yyyy/MM/dd", new ComMessage("E0037", "治疗结束日期")));
            vd.CheckItems.Add(new CheckDate(txtBookDate.Text, "yyyy/MM/dd", new ComMessage("E0037", "下次治疗日期")));
            vd.CheckItems.Add(new CheckDateRange(txtBeginDate.Text, txtEndDate.Text, "yyyy/MM/dd", new ComMessage("E0329", new string[] { "治疗开始日期", "治疗结束日期" })));
            vd.CheckItems.Add(new CheckDateRange(txtBeginDate.Text, txtBookDate.Text, "yyyy/MM/dd", new ComMessage("E0329", new string[] { "治疗开始日期", "下次治疗日期" })));
            vd.CheckItems.Add(new CheckDateRange(txtBookDate.Text, txtEndDate.Text, "yyyy/MM/dd", new ComMessage("E0329", new string[] { "下次治疗日期", "治疗结束日期" })));

            MstMemberDoctorBean beanMMD = new MstMemberDoctorBean();
            beanMMD.MemberNo = lblMemId.Text;
            beanMMD.DoctorId = Convert.ToString(ViewState["DOCTOR_ID"]);
            vd.Add(new CheckDataExists(
                new HealthTherapyDao(), HealthTherapyDao.CHECK_MEMBER_DOCTOR_METHOD, beanMMD, new ComMessage("E0901")));

            if (!vd.DoValidator())
            {
                ((Design_MasterPage)this.Master).InfoMessage = vd.ErrorMessage;
                return;
            }
                      
            // do insert update            
            HealthTherapyDao dao = new HealthTherapyDao();
            HealthTherapyBean beanHT = new HealthTherapyBean();
            if (string.IsNullOrEmpty(Convert.ToString(ViewState["CURE_ID"])))
            {
                // 登记
                beanHT.MemberNo = lblMemId.Text;
                beanHT.DoctorId = lblDocId.Text;
                beanHT.CureLevel = "0";
                beanHT.CureName = txtCureName.Text;
                beanHT.CureType = lstCureType.SelectedValue;
                beanHT.BeginDate = DateUtils.convertToDate(txtBeginDate.Text);
                beanHT.EndDate = DateUtils.convertToDate(txtEndDate.Text);
                beanHT.Frequency = Convert.ToInt32(txtFrequency.Text);
                // 下次时间
                if (string.IsNullOrEmpty(txtBookDate.Text))
                {
                    DateTime dtNext = beanHT.BeginDate.Value.AddDays(Convert.ToDouble(beanHT.Frequency));                    
                    beanHT.BespokeDate = dtNext;
                }
                else
                {
                    beanHT.BespokeDate = DateUtils.convertToDate(txtBookDate.Text);
                }
                beanHT.BespokeTime = lstBookTime.SelectedValue;
                beanHT.Memo = txtMemo.Text;
                beanHT.UserId = Convert.ToString(ViewState["USER_ID"]);   
             
                beanHT = dao.InsertPlanTherapy(beanHT);
                if (beanHT != null)
                {
                    this.ViewState["CURE_ID"] = beanHT.CureId;
                    ((Design_MasterPage)this.Master).InfoMessage =
                        HttpContext.GetGlobalResourceObject(Constants.GLOBAL_RESOURCE_NAME, "I0001").ToString();
                }
            }
            else
            {
                // 下次治疗时间 范围check
                HealthTherapyDetailBean beanCheck = new HealthTherapyDetailBean();
                beanCheck.CureId = Convert.ToInt32(ViewState["CURE_ID"]);
                beanCheck.BespokeDate = DateUtils.convertToDate(txtBookDate.Text);
                IList listChk = dao.CheckPlanNextDate(beanCheck);
                if (!(listChk == null || listChk.Count == 0))
                {
                    ((Design_MasterPage)this.Master).InfoMessage =
                        HttpContext.GetGlobalResourceObject(Constants.GLOBAL_RESOURCE_NAME, "E0330").ToString()
                        .Replace("{0}", "下次治疗日期").Replace("{1}", "上次治疗完成日期");
                    return;
                }

                // 更新
                beanHT.CureId = Convert.ToInt32(ViewState["CURE_ID"]);
                beanHT = dao.FindByMemberCureId(beanHT);
                if (beanHT == null)
                {
                    ((Design_MasterPage)this.Master).InfoMessage =
                        HttpContext.GetGlobalResourceObject(Constants.GLOBAL_RESOURCE_NAME, "E0203").ToString().Replace("{0}", "治疗计划");
                    return;
                }
                // update
                beanHT.CureName = txtCureName.Text;
                beanHT.CureType = lstCureType.SelectedValue;
                beanHT.BeginDate = DateUtils.convertToDate(txtBeginDate.Text);
                beanHT.EndDate = DateUtils.convertToDate(txtEndDate.Text);
                beanHT.Frequency = Convert.ToInt32(txtFrequency.Text);
                // 下次时间
                if (string.IsNullOrEmpty(txtBookDate.Text))
                {
                    DateTime dtNext = beanHT.BeginDate.Value.AddDays(Convert.ToDouble(beanHT.Frequency));
                    beanHT.BespokeDate = dtNext;
                }
                else
                {
                    beanHT.BespokeDate = DateUtils.convertToDate(txtBookDate.Text);
                }
                beanHT.BespokeTime = lstBookTime.SelectedValue;
                
                beanHT.Memo = txtMemo.Text;
                beanHT.UserId = Convert.ToString(ViewState["USER_ID"]);
                dao.UpdatePlanTherapy(beanHT);

                ((Design_MasterPage)this.Master).InfoMessage =
                    HttpContext.GetGlobalResourceObject(Constants.GLOBAL_RESOURCE_NAME, "I0002").ToString();
            }
        }
        catch (Exception ex)
        {
            log.Fatal(ex.StackTrace);
            log.Fatal(ex.Message);
            throw ex;
        }
    }

    // 删除按钮
    protected void btnDel_Click(object sender, EventArgs e)
    {
        try
        {
            HealthTherapyDao dao = new HealthTherapyDao();
            HealthTherapyBean beanHT = new HealthTherapyBean();
            if (!string.IsNullOrEmpty(Convert.ToString(ViewState["CURE_ID"])))
            {
                beanHT.CureId = Convert.ToInt32(ViewState["CURE_ID"]);
                beanHT = dao.FindByMemberCureId(beanHT);
                if (beanHT == null)
                {
                    ((Design_MasterPage)this.Master).InfoMessage =
                        HttpContext.GetGlobalResourceObject(Constants.GLOBAL_RESOURCE_NAME, "E0203").ToString().Replace("{0}", "治疗计划");
                    return;
                }
                int delCnt = dao.DeleteCurTherapyPlan(beanHT);
                resetFormControls();
                ((Design_MasterPage)this.Master).InfoMessage =
                    HttpContext.GetGlobalResourceObject(Constants.GLOBAL_RESOURCE_NAME, "I0003").ToString();
            }
        }
        catch (Exception ex)
        {
            log.Fatal(ex.StackTrace);
            log.Fatal(ex.Message);
            throw ex;
        }
    }

    // auto calc next date
    protected void ckbAutoCal_CheckedChanged(object sender, EventArgs e)
    {
        //if (ckbAutoCal.Checked)
        //{
        //    // next date
        //    HealthTherapyDao dao = new HealthTherapyDao();
        //    HealthTherapyDetailBean beanN = new HealthTherapyDetailBean();
        //    beanN.CureId = bean.CureId;
        //    beanN = dao.GetPlanNextDate(beanN);
        //    if (beanN != null && beanN.BespokeDate != null)
        //    {
        //        txtBookDate.Text = DateUtils.convertToString(beanN.BespokeDate.Value);
        //        lstBookTime.SelectedValue = beanN.BespokeTime;
        //    }            
        //}
        //txtBookDate.ReadOnly = ckbAutoCal.Checked;
        //txtBookDate.Focus();
    }

    // 返回按钮
    protected void btnBack_Click(object sender, EventArgs e)
    {
        string url = "~/App/Input/HealthTherapySrhForm.aspx";
        Context.Items["ParamPageIndex"] = ViewState["ParamPageIndex"];
        Context.Items["MemberNo"] = ViewState["MemberNo"];
        Context.Items["Sex"] = ViewState["Sex"];
        Context.Items["BuildingNo"] = ViewState["BuildingNo"];
        Context.Items["FloorNo"] = ViewState["FloorNo"];
        Context.Items["Room"] = ViewState["Room"];
        ControllerUtils.Transfer(Context, url, true);
    }

    // before render
    void Page_PreRender(object sender, EventArgs e)
    {
        btnDel.Enabled = false;
        if (!string.IsNullOrEmpty(Convert.ToString(ViewState["CURE_ID"])))
        {
            btnDel.Enabled = true;
        }        
    }

    // bind data to controls
    private void bindSelectData(string cureId, string membId)
    {
        HealthTherapyDao dao = new HealthTherapyDao();
        HealthTherapyBean bean = new HealthTherapyBean();

        if (!string.IsNullOrEmpty(Convert.ToString(cureId)))
        {
            // get data
            bean.CureId = Convert.ToInt32(cureId);
            bean = dao.FindByMemberCure(bean);
            if (bean != null)
            {
                lblDocId.Text = bean.DoctorId;
                lblMemId.Text = bean.MemberNo;
                lblMemName.Text = bean.MemberName;
                lblMemSex.Text = bean.MemberSex;
                lblMemTel.Text = bean.MemberTel;
                lblRoomId.Text = bean.ApartmentNo;
                lstCureType.SelectedValue = bean.CureType;
                txtCureName.Text = bean.CureName;
                
                if (bean.BeginDate != null)                
                    txtBeginDate.Text = DateUtils.convertToString(bean.BeginDate.Value);                                    
                if (bean.EndDate != null)
                    txtEndDate.Text = DateUtils.convertToString(bean.EndDate.Value);
                txtFrequency.Text = Convert.ToString(bean.Frequency);
                                
                // next date
                HealthTherapyDetailBean beanN = new HealthTherapyDetailBean();
                beanN.CureId = bean.CureId;
                beanN = dao.GetPlanNextDate(beanN);
                if (beanN != null && beanN.BespokeDate != null)
                {
                    txtBookDate.Text = DateUtils.convertToString(beanN.BespokeDate.Value);
                    lstBookTime.SelectedValue = beanN.BespokeTime;
                }
                else
                {
                    if (bean.BeginDate != null)
                    {
                        DateTime dtNext = bean.BeginDate.Value.AddDays(Convert.ToDouble(bean.Frequency));
                        txtBookDate.Text = DateUtils.convertToString(dtNext);
                        lstBookTime.SelectedValue = bean.BespokeTime;
                    }
                }
                
                txtMemo.Text = bean.Memo;
                return;
            }
        }

        // new cure plan
        ViewState["CURE_ID"] = "";
        bean = new HealthTherapyBean();
        bean.MemberNo = membId;
        bean = dao.FindByMemberId(bean);
        if (bean != null)
        {
            lblDocId.Text = bean.DoctorId;
            lblMemId.Text = bean.MemberNo;
            lblMemName.Text = bean.MemberName;
            lblMemSex.Text = bean.MemberSex;
            lblMemTel.Text = bean.MemberTel;
            lblRoomId.Text = bean.ApartmentNo;
        }
        else
        {
            ((Design_MasterPage)this.Master).InfoMessage =
                HttpContext.GetGlobalResourceObject(Constants.GLOBAL_RESOURCE_NAME, "E0203").ToString().Replace("{0}", "治疗计划");
        }
    }

    // 重置画面控件 返回新建状态
    private void resetFormControls()
    {
        if (lstCureType.Items.Count > 0) lstCureType.SelectedIndex = 0;
        txtCureName.Text = "";
        txtBeginDate.Text = "";
        txtEndDate.Text = "";
        txtFrequency.Text = "";
        txtBookDate.Text = "";
        if (lstBookTime.Items.Count > 0) lstBookTime.SelectedIndex = 0;
        txtMemo.Text = "";
        ViewState["CURE_ID"] = "";
    }

    // bind common catalog data 
    private void initPageControls()
    {
        HealthTherapyDao dao = new HealthTherapyDao();
        CommonDictionaryBean beanComDict = new CommonDictionaryBean();
        IList lstCat = null;

        // 治疗类型
        log.Fatal("\n ***** get T_MEMBER_CURE.CURE_TYPE catalog *****");
        beanComDict.Catalog = "T_MEMBER_CURE.CURE_TYPE";
        lstCat = dao.FindByCatalog(beanComDict);
        lstCureType.Items.Clear();
        bindDataToListControl("lstCureType", lstCat);

        // 预约时间
        lstBookTime.Items.Clear();
        for (int i = 1; i <= 24; i++)
        {
            string strTime;
            string strText;
            string strValue;

            if ((i + 8) < 10)
            {
                strTime = "0" + (i + 8) + ":00";
            }
            else
            {
                strTime = ((i + 8) % 24) + ":00";
            }
            strText = strTime;
            strValue = Convert.ToString((i + 8) % 24);
            ListItem item = new ListItem(strText, strText);
            lstBookTime.Items.Add(item);
        }
    }

    // bind db data to selected controls
    private void bindDataToListControl(string ControlId, IList LstData)
    {
        if (LstData == null || LstData.Count == 0) return;

        foreach (CommonDictionaryBean bean in LstData)
        {
            if (this.Master.FindControl("ContentPlaceHolder1").FindControl(ControlId) is DropDownList)
            {
                ((DropDownList)this.Master.FindControl("ContentPlaceHolder1").FindControl(ControlId)).Items.Add(new ListItem(bean.Content, bean.DictNo.ToString()));
            }
            else if ((this.Master.FindControl("ContentPlaceHolder1").FindControl(ControlId) is CheckBoxList)
                || (this.Master.FindControl("ContentPlaceHolder1").FindControl(ControlId) is RadioButtonList))
            {
                ((ListControl)this.Master.FindControl("ContentPlaceHolder1").FindControl(ControlId)).Items.Add(new ListItem(bean.Content, bean.DictNo.ToString()));
            }
        }
    }
    
}
